<template>
  <div class="container">
    <div class="logo">
      <img src="https://picsum.photos/200/200?random=1" alt="Logo" />
      <h1>用户登录</h1>
    </div>
    <div class="form-container">
      <van-form>
        <van-field
          v-model="form.username"
          name="username"
          label="账号"
          placeholder="请输入账号"
          required
        />
        <van-field
          v-model="form.password"
          name="password"
          label="密码"
          type="password"
          placeholder="请输入密码"
          required
        />
        <div class="btn-group">
          <van-button type="primary" native-type="submit" @click="onSubmit">登录</van-button>
          <van-button type="default" @click="goRegister">注册账号</van-button>
        </div>
      </van-form>
    </div>
  </div>
</template>

<script>
import { login } from '@/api/user';
import token from '@/utils/token';


export default {
  data() {
    return {
      form: {
        username: '',
        password: ''
      }
    }
  },
  methods: {
    /* 登录表单提交 */
    onSubmit() {
      // 表单校验
      if (!this.form.username || !this.form.password) {
        this.$toast.fail('请填写账号和密码');
        return;
      }
      // 发送登录请求
      login(this.form).then(res => {
        // 判断登录结果
        if (res.code !== 200) {
          this.$toast.fail(res.msg);
          return;
        }
        // 登录成功
        this.$toast.success(res.msg);
        // 存token
        token.setToken(res.data);

        // 跳转到首页
        this.$router.push('/home');
      }).catch(err => {
        // 登录失败
        this.$toast.fail('登录失败');
      });
    },
    /* 去注册页面 */
    goRegister() {
      this.$router.push('/register');
    }
  }
}
</script>

<style scoped>
/* 容器样式 */
.container {
  padding: 20px;
  max-width: 400px;
  margin: 0 auto;
}
/* logo样式 */
.logo {
  text-align: center;
  margin: 50px 0;
}
/* logo图片样式 */
.logo img {
  width: 100px;
  height: 100px;
  border-radius: 50%;
}
/* 表单样式 */
.form-container {
  background: #fff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 0 10px rgba(0,0,0,0.1);
}
/* 按钮组样式 */
.btn-group {
  margin-top: 20px;
  display: flex;
  gap: 15px;
}
</style>  